<script setup lang="ts">
import type { VxeGridProps } from '@vben/plugins/vxe-table';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import { TabPane, Tabs } from 'ant-design-vue';

import { saleOrderInfo } from '#/api/hm/saleOrder';
import { saleOrderRefundList } from '#/api/hm/saleOrderRefund';
import { Description, useDescription } from '#/components/description';

import { columns, descSchema } from '../info';

const activeKey = ref('1');
const [BasicModal, modalApi] = useVbenModal({
  draggable: true,
  onOpenChange: handleOpenChange,
  onClosed: () => {
    modalApi.close();
    activeKey.value = '1';
  },
});

const [registerDescription, { setDescProps }] = useDescription({
  column: 2,
  labelStyle: {
    minWidth: '100px',
    width: '100px',
  },
  schema: descSchema,
});
const saleId = ref('');
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns,
  height: '400',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const param = {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          saleId: saleId.value,
        };
        const data = await saleOrderRefundList(param);
        return data;
      },
    },
  },
  rowConfig: {
    keyField: 'refund_id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'hm-saleOrderRefundList-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  gridOptions,
});

async function handleOpenChange(open: boolean) {
  if (!open) {
    return null;
  }
  modalApi.modalLoading(true);

  const { saleOrderId } = modalApi.getData() as {
    saleOrderId: number | string;
  };
  saleId.value = saleOrderId as string;
  const response = await saleOrderInfo(saleOrderId);
  // 处理赠品
  if (response.isGift === 'Y' && response.giftList) {
    response.giftProductName1 = response.giftList[0]?.giftProductName;
    response.giftProductName2 = response.giftList[1]?.giftProductName;
    response.giftProductName3 = response.giftList[2]?.giftProductName;
    response.giftNum1 = response.giftList[0]?.giftNum;
    response.giftNum2 = response.giftList[1]?.giftNum;
    response.giftNum3 = response.giftList[2]?.giftNum;
  }
  // 赋值
  setDescProps({ data: response });

  modalApi.modalLoading(false);
}
</script>

<template>
  <BasicModal
    :footer="false"
    :fullscreen-button="false"
    title="订单详情"
    class="w-[800px]"
  >
    <Tabs v-model:active-key="activeKey">
      <TabPane tab="订单详情" key="1">
        <Description @register="registerDescription" />
      </TabPane>
      <TabPane tab="退货列表" key="2">
        <BasicTable table-title="退货退款列表" />
      </TabPane>
    </Tabs>
  </BasicModal>
</template>
